<template>
  <div class="coordinateMap">
    <div
      id="map"
      class="map"
    >
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader"
export default {
  data() {
    return {
      marker: null,
      lng: '',
      lat: '',
      map:'',
      AMap:'',//构造函数保存
      geocoder:null,//保存地理位置解析的实例
    }
  },
  mounted() {
    this.initMap()
    //监听用户的点击事件
   
  },
  methods: {
    //从外面组件 调取initMap方法
    initMap(lal=0) {
        // console.log(lal)
        const me =this;
        AMapLoader.load({
            // key:'3d35ef62d78d0d0015b33452a0789b2a',
            key:'xxxxxxxxxxxxxxxxxx',//这个key需要在高德开放平台申请而且是web jsapi 注意不是web服务 https://console.amap.com/dev/key/app
            plugins:['AMap.Geocoder']//这个是使用坐标转换成地址的插件
        }).then(AMap=>{
                me.AMap = AMap
                me.map =new me.AMap.Map('map', {
                resizeEnable: true, //是否监控地图容器尺寸变化
                zoom: 11, //初始化地图层级
                center:[106.610443,26.664922] //初始化地图中心点
            }); 
            //如果有经纬度就显示经纬度的标记
            if(lal){
                this.marker = new AMap.Marker({
                  position: new AMap.LngLat(lal[0], lal[1])
                });
                 me.map.add(this.marker);
            }
            // console.log(AMap,'address')
            me.geocoder =  new AMap.Geocoder();//保存实例
                //  me.addDot(lal)
             me.map.on('click', (e) => {
            me.lng = e.lnglat.getLng()
            me.lat = e.lnglat.getLat()
            me.addDot()
            })
        })

    },
    lnglatChange() {
      this.addDot()
      //自适应中心点
      this.map.setFitView();
    },
    //增加点标记
    addDot(lal){
       if (this.marker ) {
        this.marker.setMap(null);
        this.marker = null;
      }
      if(lal){
          let long = Number(lal.split[','][0])
          let lat = Number(lal.split[','][1])
          this.marker = new this.AMap.Marker({
             position: new this.AMap.LngLat(long, lat)
            }); 
            this.map.add(this.marker);
            return
      }
      this.marker = new this.AMap.Marker({
        position: new this.AMap.LngLat(this.lng, this.lat)
      });
      let lnglat = this.lng +','+this.lat;
      this.geocoder.getAddress(lnglat.split(','),(status,result)=>{
          if (status === 'complete'&&result.regeocode) {
                const address = result.regeocode.formattedAddress;
                 this.$emit("giveLnglat", lnglat);
                 this.$emit("address", address);
               this.map.add(this.marker);
            }else{
                console.error('根据经纬度查询地址失败')
            }

      })
     
    },
  }
}
</script>

<style lang="scss" scoped>
.coordinateMap {
  width: 500px;
  .map {
    width: 500px;
    height: 300px;
    border-radius:6px;
  }
}
</style>